# coding:utf-8
__author__ = 'admin zhoushuang'
__date__ = '2016/9/28'

import gvars
import os
from base_handler import *
from common_functions import *


class mod_basecmd(BaseHandler):
    """ Executed simple and safe shell commands

    The allowed shell commands is defined in Gvars.BASECMD
    Request Parameters:
        module  = mod_basecmd
        cmdline = ...               # shell cmd
    """

    def __init__(self):
        super(mod_basecmd, self).__init__()
        pass

    def handle(self, reqdict):
        try:
            params = extract_param(reqdict, (('cmdline', 1),))
        except ValueError:
            self.echo.write("#ERROR\tParameter is wrong. reqdict = {} \n".format(reqdict))

        cmdline = params['cmdline']
        if not cmdline:
            self.echo.write('#ERROR cmdline is none\n')
        cmds = cmdline.split('|')
        flag = True
        for c in cmds:
            cn = c.split()[0].strip()
            if cn not in gvars.BASECMD:
                flag = False
                self.echo.write('#ERROR {} is not a base commond\n'.format(cn))
                break

        if flag:
            pipe = os.popen(cmdline)
            self.echo.write('########## {:^40}##########\n'.format(cmdline))
            out = pipe.read()
            # print out
            self.echo.write(out)
            ret = pipe.close()
            if ret:
                self.echo.write('#FAILED RETURN CODE:{}\n'.format(bytes(ret)))
            self.echo.write('########## SUCCESS ##########\n')
        pass


def gethandler():
    return gethandler.cache


gethandler.cache = mod_basecmd()
